package com.aier.user.action.pay.unionpay;


import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aier.admin.common.AdminUtil;
import com.aier.common.common.Constant;
import com.aier.user.action.UserBaseAction;
import com.aier.user.action.pay.unionpay.conf.UpmpConfig;
import com.aier.user.action.pay.unionpay.service.UpmpService;
import com.aier.user.entity.userapp.Bill;
import com.aier.user.service.IUserBuyService;

@Scope("prototype")
@Component("userUnionpayAction")
public class UserUnionpayAction extends UserBaseAction {

    private static final long serialVersionUID = 1L;
    
    
    @Resource(name = "userBuyService")
    private IUserBuyService userBuyService;

    private int s;
    // 订单id
    private Long bill_id;
    private String union_tn;
    
    
    @Override
    public String execute() {
        return SUCCESS;
    }

    /**
     * 订单推送请求,获取交易流水号
     * @return
     */
    public String UnionpayPurchase(){
        Bill bill = userBuyService.searchBillById(bill_id);
//        Commidity commidity = userBuyService.searchCommidity(bill.getCid());
        
        Map<String, String> req = new HashMap<String, String>();
        req.put("version", UpmpConfig.VERSION);// 版本号
        req.put("charset", UpmpConfig.CHARSET);// 字符编码
        req.put("transType", "01");// 交易类型
        req.put("merId", UpmpConfig.MER_ID);// 商户代码
        req.put("backEndUrl", aier_url + UpmpConfig.MER_BACK_END_URL);// 通知URL
        req.put("frontEndUrl", aier_url + UpmpConfig.MER_FRONT_END_URL);// 前台通知URL(可选)
        req.put("orderDescription", "订单描述");// 订单描述(可选)
        req.put("orderTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));// 交易开始日期时间yyyyMMddHHmmss
        req.put("orderTimeout", "");// 订单超时时间yyyyMMddHHmmss(可选)
        req.put("orderNumber", generateOrdrNo(""+bill_id));//订单号(商户根据自己需要生成订单号)
        req.put("orderAmount", "1");// 订单金额
        req.put("orderCurrency", "156");// 交易币种(可选)
        req.put("reqReserved", "透传信息");// 请求方保留域(可选，用于透传商户信息)
                
        // 保留域填充方法
        Map<String, String> merReservedMap = new HashMap<String, String>();
        merReservedMap.put("test", "test");
        req.put("merReserved", UpmpService.buildReserved(merReservedMap));// 商户保留域(可选)
        
        Map<String, String> resp = new HashMap<String, String>();
        boolean validResp = UpmpService.trade(req, resp);
           
        // 商户的业务逻辑
        if (validResp){
            // 服务器应答签名验证成功
            s = 1;
            union_tn = resp.get("tn");
        }else {
            // 服务器应答签名验证失败
            s = 0;
        }
        
        return SUCCESS;
        
    }
    

    /**
     * 接收通知并处理 异步通知
     * @return
     * @throws Exception 
     */
    public String UnionpayNotifyReceiver() throws Exception{
        //获取银联POST过来异步通知信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        PrintWriter out = null;
        out = response.getWriter();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        if(UpmpService.verifySignature(params)){// 服务器签名验证成功
            //请在这里加上商户的业务逻辑程序代码
            //获取通知返回参数，可参考接口文档中通知参数列表(以下仅供参考)
            String transStatus = request.getParameter("transStatus");// 交易状态
            String orderNumber = request.getParameter("orderNumber");// 商户订单号
            orderNumber = leftDeling(orderNumber);
            if (null != transStatus && transStatus.equals("00")) {
                // 交易处理成功
                System.out.println("后台交易付款成功");
                userBuyService.updateBuyServiceSuccess(Long.valueOf(orderNumber));

            } else {
                System.out.println("后台交易付款失败");
            }
            out.println("success");
        }else{// 服务器签名验证失败
            out.println("fail");
        }
        out.flush();
        out.close();    
        return SUCCESS;
    }

    /**
     * 接收通知并处理 前台通知
     * @return
     * @throws Exception 
     */
    public String UnionpayRenturnReceiver() throws Exception{
        //获取银联POST过来异步通知信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        PrintWriter out = null;
        out = response.getWriter();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        if(UpmpService.verifySignature(params)){// 服务器签名验证成功
            //请在这里加上商户的业务逻辑程序代码
            //获取通知返回参数，可参考接口文档中通知参数列表(以下仅供参考)
            String transStatus = request.getParameter("transStatus");// 交易状态
            String orderNumber = request.getParameter("orderNumber");// 商户订单号
            orderNumber = leftDeling(orderNumber);
            if (null != transStatus && transStatus.equals("00")) {
                // 交易处理成功
                System.out.println("前台交易付款成功");
                //userBuyService.updateBuyServiceSuccess(Long.valueOf(orderNumber));

            } else {
                System.out.println("前台交易付款失败");
            }
            out.println("success");
        }else{// 服务器签名验证失败
            out.println("fail");
        }
        out.flush();
        out.close();    
        return SUCCESS;
    }
    
    

    /**
     * 订单号生成，8-40位，根据订单id在左边补足0
     * @return
     */
    public static String generateOrdrNo(String bill_id){
        String returnstr = AdminUtil.leftPading(bill_id, "0", Constant.num_8);
        System.out.println(returnstr);
        return returnstr;
        
    }
    
    /**
     * 去除左边的0
     * @param tmpStr
     * @return
     */
    public static String leftDeling(String tmpStr){
        if("0".equals(tmpStr.charAt(0)+"")&&tmpStr.length()>1){
            return leftDeling(tmpStr.substring(1));
        }else{
            return tmpStr;
        }
    }
    
    
    public void setUserBuyService(IUserBuyService userBuyService) {
        this.userBuyService = userBuyService;
    }


    public int getS() {
        return s;
    }


    public void setBill_id(Long bill_id) {
        this.bill_id = bill_id;
    }

    public String getUnion_tn() {
        return union_tn;
    }


}
